package models

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"gitee.com/hardykay/AnalysisLampLog/conn"
	"gorm.io/gorm"
	"time"
)

const DbNameRunSql = "run_sql"

type RunSql struct {
	RunTime time.Time `gorm:"column:run_time" json:"run_time"`
	Sql     string    `gorm:"column:sql" json:"sql"`
	Md5     string    `gorm:"column:md5" json:"md5"`
	Feature string    `gorm:"column:feature" json:"feature"`
}

func (*RunSql) TableName() string {
	return DbNameRunSql
}

// Create 新增
func (m *RunSql) Create() (err error) {
	if len(m.Sql) == 0 {
		return
	}
	s := fmt.Sprintf("%s-%s", m.RunTime.Format("2006-01-02 15:04:05"), m.Sql)
	hash := md5.Sum([]byte(s))
	// 将哈希值转换为十六进制字符串
	m.Md5 = hex.EncodeToString(hash[:])
	err = conn.DBObj.Create(m).Error
	if err != nil {
		err = fmt.Errorf("新增%s失败: %w", m.TableName(), err)
		return
	}
	return
}

// One 获取
func (m *RunSql) One(db *gorm.DB, md5 string) (err error) {
	err = db.Where("md5=?", md5).Take(m).Error
	if err != nil {
		err = fmt.Errorf("获取%s失败: %w", m.TableName(), err)
		return
	}
	return
}
